package org.taobao.ibatiside.ui.view;

import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import org.taobao.ibatiside.core.filemodel.IbatisConfigFile;
import org.taobao.ibatiside.core.filemodel.IbatisMapperFile;
import org.taobao.ibatiside.core.filemodel.IbatisStatement;
import org.taobao.ibatiside.ui.action.AbstractViewerAction;

public class OpenIbatisFileAction extends AbstractViewerAction {

	private void expand(Object selection) {
		if (this.viewer.getExpandedState(selection)) {
			this.viewer.collapseToLevel(selection, 1);
		} else {
			this.viewer.expandToLevel(selection, 1);
		}
	}
	 public void run ()
		{
	    	Object selection = getSelectObject();
	    	String xml_editor_id = "org.eclipse.wst.xml.ui.internal.tabletree.XMLMultiPageEditorPart";
	    	if (selection instanceof IbatisConfigFile)
	    	{
	    		IFile file = ((IbatisConfigFile)selection).getConfigFile();
	    		if (file != null && file.exists()){
	    			try {
						PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(new FileEditorInput(file), xml_editor_id);
					} catch (PartInitException e) {
						e.printStackTrace();
					}
	    		}
	    	}else if (selection instanceof IbatisMapperFile){
	    		IFile file = ((IbatisMapperFile)selection).getSqlmapFile();
	    		if (file != null && file.exists()){
	    			try {
						PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(new FileEditorInput(file), xml_editor_id);
					} catch (PartInitException e) {
						e.printStackTrace();
					}
	    		}
	    	}else if(selection instanceof IbatisStatement){
	    		IbatisStatement stmt = (IbatisStatement)selection;
				IFile file = ((IbatisMapperFile)stmt.getParent()).getSqlmapFile();
//	    		System.out.println("My:["+stmt.getOffset()+","+stmt.getLength()+"]");
	    		if (file != null && file.exists()){
	    			try {
						IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(new FileEditorInput(file), xml_editor_id);
						ITextEditor sse = (ITextEditor) editor.getAdapter(ITextEditor.class);
						if (sse != null){
							sse.selectAndReveal(stmt.getOffset(), stmt.getLength());
						}
					} catch (PartInitException e) {
						e.printStackTrace();
					}
	    		}
	    	}
	    	else
	    	{
	    		expand(selection);
	    	}
		}
}
